<!-- 补单核算作业：蹇泽阳 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find :searchImg="false" :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findClicked2" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <h1 class="f16">补料单资料</h1>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @selectList="selectTableList"
          @currentRow="currentRow"
          @confirmChange="confirmChange"
        />
        <PageModule
          :PageData="{ total, pageSizeShow: true, buttonS: true }"
          :layout="'prev, pager'"
          @pageSizeChange="handleSizeChange"
          @pageChange="handleCurrentChange"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex">
          <h1 class="f16">补料明细</h1>
          <el-button type="primary" class="primaryBth ml10" @click="fillUnitPrice" :disabled="fillUnitPriceDisabled">填充单价</el-button>
        </div>
        <Table
          :tableHeader="tableHeader2"
          :tableData="tableData2"
          class="mt10"
          :isLoading="isLoading2"
          @inputChange="confirmChange2"
          @currentRow="currentRow2"
          :TableHeight="50"
        />
        <div class="flex">
          <h1 class="f16">责任归属汇总</h1>
          <JDialog
            v-if="!fillUnitPriceDisabled"
            :tableHeader="tableHeader3"
            :width="60"
            :currentTableRow="currentTableRow3"
            @confirm="confirm3"
            :unAdd="true"
            :unEdit="false"
            :unSub="true"
          />
        </div>
        <Table :tableHeader="tableHeader3" :tableData="tableData3" :isLoading="isLoading2" @currentRow="currentRow3" :TableHeight="50" />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" class="mt10">
        <h1 class="f16">贴合子材料明细</h1>
        <Table
          :tableHeader="tableHeader4"
          :tableData="tableData4"
          class="mt10"
          :isLoading="isLoading4"
          :summaryData="summaryData4"
          summary
          :TableHeight="31"
        />
        <h1 class="f16">贴合子材料明细2</h1>
        <Table
          :tableHeader="tableHeader5"
          :tableData="tableData5"
          class="mt10"
          :isLoading="isLoading5"
          :summaryData="summaryData5"
          summary
          :TableHeight="31"
        />
        <h1 class="f16">人工费用明细</h1>
        <Table :tableHeader="tableHeader6" :tableData="tableData6" class="mt10" :isLoading="isLoading6" :TableHeight="31" />
      </el-card>
    </div>

    <!-- 打印 -->
    <div v-show="false" class="printContent2" style="page-break-after: always">
      <div style="width: 100%; height: 11.5cm">
        <div class="mainTable header size-24" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px">
          <div>已审核</div>
          <div style="text-align: center">
            <span style="text-align: center; margin-left: 110px">{{ factoryName }} 补料核算单</span>
            <span style="text-align: center; margin-left: 50px; font-size: 14px">打印日期：{{ getCurrentTime() }}</span>
          </div>
        </div>
        <div class="mainTable header" style="display: flex; justify-content: space-between">
          <span>补料单号：{{ printData.slipNo }}</span>
          <span>指令号：{{ printData.lotNo }}</span>
          <span>补制日期：{{ printData.sysDate }}</span>
          <span>补制单位：{{ printData.dutyDeptName }}</span>
          <span>开单人：{{ printData.sysUser }}</span>
        </div>
        <div class="mainTable header" style="display: flex; justify-content: space-between">
          <span>备注说明：{{ printData.dutyMemo }}</span>
          <span>补料类型：{{ printData.blFlag }}</span>
        </div>
        <!-- 以上是页头 -->
        <section class="mainTable" style="border: 1px solid black; margin-top: 10px">
          <div style="display: flex">
            <span style="margin-right: 30px">指令：{{ printData.lotNo }}</span>
            <span style="margin-right: 30px">型体：{{ printData.style }}</span>
            <span style="margin-right: 30px">颜色：{{ printData.color }}</span>
            <span style="margin-right: 30px">指令数：{{ printData.orderQty }}</span>
          </div>
          <div style="display: flex; margin-top: 5px" v-for="item in printData.part">
            <span>{{ item }}</span>
          </div>
        </section>
        <div class="mainTable" style="margin-top: 10px">
          <table style="text-align: center; font-size: 16px; margin-top: 10px">
            <tr>
              <td class="size-14 center">材料颜色</td>
              <td class="size-14 center">材料名称</td>
              <td class="size-14 center">材料规格</td>
              <td class="size-14 center">单位</td>
              <td class="size-14 center">开补耗量</td>
              <td class="size-14 center">原仓应发</td>
              <td class="size-14 center">责任用量</td>
              <td class="size-14 center">单价</td>
              <td class="size-14 center">责任归属/用量（责任金额）</td>
            </tr>
            <tr v-for="(item, index) in printData.mtlList" :key="index">
              <td class="size-14 center">{{ item.mtlColor }}</td>
              <td class="size-14 center">{{ item.mtlName }}</td>
              <td class="size-14 center">{{ item.mtlSpec }}</td>
              <td class="size-14 center">{{ item.mtlUnit }}</td>
              <td class="size-14 center">{{ item.reqQty }}</td>
              <td class="size-14 center">{{ item.actQty }}</td>
              <td class="size-14 center">{{ item.actQty1 }}</td>
              <td class="size-14 center">{{ item.price }}</td>
              <td class="size-14 center">{{ item.remark }}</td>
            </tr>
          </table>
        </div>
        <div class="mainTable" style="margin-top: 10px">
          <table style="text-align: center; font-size: 16px; margin-top: 10px">
            <tr>
              <td class="size-14 center">责任归属</td>
              <td class="size-14 center">部门</td>
              <td class="size-14 center">责任用量</td>
              <td class="size-14 center">责任金额</td>
              <td class="size-14 center">人工费用</td>
              <td class="size-14 center">扣款金额</td>
            </tr>
            <tr v-for="(item, index) in printData.dutyList" :key="index">
              <td class="size-14 center">{{ item.dutyName }}</td>
              <td class="size-14 center">{{ item.deptName }}</td>
              <td class="size-14 center">{{ item.dutyQty }}</td>
              <td class="size-14 center">{{ item.dutyAmt }}</td>
              <td class="size-14 center">{{ item.laborAmt }}</td>
              <td class="size-14 center">{{ item.amt }}</td>
            </tr>
          </table>
        </div>
        <div>
          <div class="header mainTable" style="display: flex; justify-content: start; margin-top: 10px">
            <span>核签：</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import { formateData } from '@/plugins/mixinJ'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'AccountingOperationsForSupplementaryOrders'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import type { formListType } from '@/components/Find/index.vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
const fillUnitPriceDisabled = ref(false)
// 通过sessionStorage获取工厂名称
const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}')
const factoryName = userInfo.abbrName
function transformStr(money: any) {
  var cnMoney = '零元整'
  var strOutput = ''
  var strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分'
  money += '00'
  var intPos = money.indexOf('.')
  if (intPos >= 0) {
    money = money.substring(0, intPos) + money.substr(intPos + 1, 2)
  }
  strUnit = strUnit.substr(strUnit.length - money.length)
  for (var i = 0; i < money.length; i++) {
    strOutput += '零壹贰叁肆伍陆柒捌玖'.substr(money.substr(i, 1), 1) + strUnit.substr(i, 1)
  }
  cnMoney = strOutput
    .replace(/零角零分$/, '整')
    .replace(/零[仟佰拾]/g, '零')
    .replace(/零{2,}/g, '零')
    .replace(/零([亿|万])/g, '$1')
    .replace(/零+元/, '元')
    .replace(/亿零{0,3}万/, '亿')
    .replace(/^元/, '零元')
  return cnMoney
}
const getCurrentTime = () => {
  const date = new Date()
  const year = date!.getFullYear()
  const month = String(date!.getMonth() + 1).padStart(2, '0') // 使用padStart确保月份是两位数
  const day = String(date!.getDate()).padStart(2, '0') // 使用padStart确保日期是两位数
  const hours = String(date!.getHours()).padStart(2, '0') // 小时
  const minutes = String(date!.getMinutes()).padStart(2, '0') // 分钟
  const seconds = String(date!.getSeconds()).padStart(2, '0') // 秒
  // 返回格式化的日期时间字符串
  return `${year}-${month}-${day}`
}
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '补料单号',
    inputValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '补料部门',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'date',
    dateLabel: '补料日期',
    dateValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '补料类型',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '开单用户',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '指令',
    inputValue: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '未确认',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已确认',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '有标记',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '无标记',
    checked: true
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
]) as any

const formList2 = ref([
  {
    type: 'select',
    selectValue: '',
    selectP: '起始节点',
    selectOptions: [
      { optionKey: '仓储', optionLabel: '仓储', optionValue: '仓储' },
      { optionKey: '冲裁', optionLabel: '冲裁', optionValue: '冲裁' },
      { optionKey: '手工', optionLabel: '手工', optionValue: '手工' },
      { optionKey: '外发', optionLabel: '外发', optionValue: '外发' },
      { optionKey: '针车', optionLabel: '针车', optionValue: '针车' },
      { optionKey: '成型', optionLabel: '成型', optionValue: '成型' }
    ]
  },
  {
    disabled: false,
    type: 'button',
    checkboxLabel: '取材料单价'
  },
  {
    disabled: false,
    type: 'button',
    checkboxLabel: '计算责任金额'
  },
  {
    disabled: false,
    type: 'button',
    checkboxLabel: '计算人工费用'
  },
  {
    type: 'button',
    checkboxLabel: '打勾记录补单检核'
  },
  {
    type: 'button',
    checkboxLabel: '打勾记录取消检核'
  },
  {
    type: 'button',
    checkboxLabel: '打印补料核算单'
  }
]) as any

// 表一模块
// 表一按钮
const findClicked = (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
}
// 每页显示的行数
let rowsPerPage = 0
// 计算总页数
const totalPages = ref(0)
const isLastPage = (pageIndex: number, totalPages: number) => {
  return pageIndex === totalPages - 1
}
const mergedData = ref([]) as any
const printData = ref([]) as any
const pages = async () => {
  printData.value = await service.get<any, any>(`/mtlCosts/print/cfm?slipNo=${currentTableRow.value.slipNo}&lotNo=${currentTableRow.value.lotNo}`)
  // mergedData.value = tableDataList.dtos
  rowsPerPage = 11

  // 设置总页数
  // totalPages.value = printArr.value.length
}
const printArr = ref([]) as any
const printSummary = async () => {
  setTimeout(() => {
    const qrCodeContainer = document.querySelector<any>('.printContent2')
    if (qrCodeContainer) {
      qrCodeContainer.style.display = 'block'
      const printWindow = window.open('', '_blank')
      printWindow!.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>&nbsp;</title>
          <link rel="stylesheet" type="text/css" href="print.css" media="print">
          <style>
            body, html {
              margin: 0;
              padding: 0;
            }
            @page {
              size: auto;
            }
            @media print {
                /* 打印时的样式 */


                /* 其他打印样式 */
            }
            h2 {
                    margin-left: initial; /* 或者设置适合打印的左边距 */
                    page-break-inside: avoid; /* 避免在h2元素内部分页 */
                }
            .headerTable {
                height: auto;
                border: 0px solid #000;
                text-align: center;
                display: flex;
                margin: 20px 20px 0px;
                vertical-align: top;
            }

            .title {
                display: flex;
                justify-content: center;
                margin-bottom: 10px;
            }

            .center {
                text-align: center;
            }

            .right {
                text-align: right;
            }

            .left {
                text-align: left;
            }

            .no-padding {
                padding: 0;
            }

            .no-margin {
                margin: 0;
            }

            .margin-5 {
                margin: 5px;
            }

            .margin-top-5 {
                margin-top: 5px;
            }

            .margin-top-15 {
                margin-top: 15px;
            }

            .size-8 {
                font-size: 8px !important;
            }

            .size-10 {
                font-size: 10px;
            }

            .size-12 {
                font-size: 12px;
            }

            .size-14 {
                font-size: 14px;
            }

            .size-16 {
                font-size: 17px;
            }

            .size-18 {
                font-size: 18px;
            }

            .size-24 {
                font-size: 24px;
            }

            #date-tip {
                position: relative;
            }

            span.tip {
                display: inline-block;
                height: 14px;
                line-height: 14px;
                margin-right: 30px;
            }

            table {
                font-size: 10px;
                border-collapse: collapse;
                border-spacing: 0;
                border-collapse: collapse;
                border-spacing: 0;
                empty-cells: show;
                width: 100%;
            }

            table th,
            table td {
                border: 1px solid #000;
                font-size: 12px;
            }

            table.no-border,
            table.no-border th,
            table.no-border td {
                border: 0px;
            }

            table td.no-left-border {
                border-left: 0px;
            }

            table td.no-right-border {
                border-right: 0px;
            }

            .mainTable {
                margin: 0 20px;
            }

            /* 可以在这里添加更多自定义的打印样式 */
          </style>
        </head>
        <body>
    `)

      // 将 .qrCodeContainer 的内容复制到打印窗口的 body 中
      const cloneContainer = qrCodeContainer.cloneNode(true)
      printWindow!.document.body.appendChild(cloneContainer)

      printWindow!.document.write(`
        </body>
      </html>
    `)
      printWindow!.document.close()

      // 开始打印
      printWindow!.print()

      // 打印完成后，可以恢复 .qrCodeContainer 的原始显示状态
      qrCodeContainer.style.display = 'none'
    }
  }, 600)
}
const findClicked2 = async (content: string) => {
  if (content === '打印补料核算单') {
    await pages()

    setTimeout(() => {
      printSummary()
    }, 1000)
  }
  if (content === '取材料单价') {
    const res = (await LoginWork.post(
      `/mtlCosts/suppCostComp?type=${1}&slipNo=${currentTableRow.value.slipNo}&dept=${formList2.value[0].selectValue}`
    )) as any
    if (res.code === 200) {
      JMessage.success('取材料单价成功')
      currentRow(currentTableRow.value)
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '计算责任金额') {
    const res = (await LoginWork.post(
      `/mtlCosts/suppCostComp?type=${2}&slipNo=${currentTableRow.value.slipNo}&dept=${formList2.value[0].selectValue}`
    )) as any
    if (res.code === 200) {
      JMessage.success('计算责任金额成功')
      currentRow(currentTableRow.value)
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '计算人工费用') {
    const res = (await LoginWork.post(
      `/mtlCosts/suppCostComp?type=${3}&slipNo=${currentTableRow.value.slipNo}&dept=${formList2.value[0].selectValue}`
    )) as any
    if (res.code === 200) {
      JMessage.success('计算人工费用成功')
      currentRow(currentTableRow.value)
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '打勾记录补单检核') {
    if (selectedLists.value.length === 0) {
      JMessage.error('请选择需要打勾的记录')
      return
    }
    const res = (await LoginWork.post(`/mtlCosts/suppFinalCheck?type=${1}&slipNos=${selectedLists.value.map((item: any) => item.slipNo)}`)) as any
    if (res.code === 200) {
      JMessage.success('补单检核成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '打勾记录取消检核') {
    if (selectedLists.value.length === 0) {
      JMessage.error('请选择需要打勾的记录')
      return
    }
    const res = (await LoginWork.post(`/mtlCosts/suppFinalCheck?type=${0}&slipNos=${selectedLists.value.map((item: any) => item.slipNo)}`)) as any
    if (res.code === 200) {
      JMessage.success('取消补单检核成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
}
const tableData = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 表格计算函数
const cfmFlag = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '已确认')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '未确认')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return ''
  } else if (Unaudited.checked) {
    return 1
  } else if (Audited.checked) {
    return 0
  } else {
    ElMessage('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return ''
  }
}
const cfmFlag2 = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '有标记')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '无标记')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return ''
  } else if (Unaudited.checked) {
    return 1
  } else if (Audited.checked) {
    return 0
  } else {
    ElMessage('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return ''
  }
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/mtlCosts/suppHeadQuery', {
    blFlag: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '补料类型')
      ?.selectValue,
    dutyDeptNo: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '补料部门')
      ?.selectValue, //补料部门ID
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '指令'
    )?.inputValue,
    slipDateEnd: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '补料日期'
    )?.dateValue?.[1],
    slipDateStart: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '补料日期'
    )?.dateValue?.[0],
    slipNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '补料单号'
    )?.inputValue,
    sysUser: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '开单用户'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    finFlag: cfmFlag(),
    cwFlag: cfmFlag2()
    // shortStatus: cfmFlag(), //	有无欠数(Y/N)	string	body	true
  })
  isLoading.value = false
  tableData.value = tableDataList.dtos.map((item: any) => {
    if (item.cwRek !== null) item.financeFlag = 'Y'
    if (item.financeFlag2 === 'Y') item.backgroundColor = '#80FF00'
    item.change = true
    return item
  })
  total.value = tableDataList.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
const tableHeader = ref([
  {
    change: true,
    backgroundColor: true,
    width: '120px',
    label: '补料单号',
    prop: 'slipNo'
  },
  {
    change: true,
    label: '补料日期',
    prop: 'slipDate'
  },
  {
    change: true,
    label: '补料部门',
    prop: 'dutyDeptName'
  },
  {
    change: true,
    label: '审核日期',
    prop: 'financeDate'
  },
  {
    change: true,
    label: '指令',
    prop: 'lotNo'
  },
  {
    change: true,
    label: '型体',
    prop: 'style'
  },
  {
    change: true,
    label: '人工费用',
    prop: 'laborFee'
  },
  {
    change: true,
    label: '财务标记',
    prop: 'financeFlag'
  },
  {
    change: true,
    label: '补料类型',
    prop: 'blFlag'
  },
  {
    change: true,
    label: '开单用户',
    prop: 'sysUser'
  },
  {
    change: true,
    label: '备注说明',
    prop: 'dutyMemo'
  },
  {
    change: true,
    width: '150px',
    label: '退单说明',
    prop: 'returnRek'
  },
  {
    label: '财务备注',
    prop: 'cwRek'
  }
])
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
  getTableList2()
  if (row.financeFlag2 === 'Y') {
    fillUnitPriceDisabled.value = true
    formList2.value[0].disabled = true
    formList2.value[1].disabled = true
    formList2.value[2].disabled = true
  } else {
    fillUnitPriceDisabled.value = false
    formList2.value[0].disabled = false
    formList2.value[1].disabled = false
    formList2.value[2].disabled = false
  }
}
const selectedLists = ref([])
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}
const confirmChange = async (row: any) => {
  const res = (await LoginWork.put(`/mtlCosts/suppRekUpdate?slipNo=${row.slipNo}&cwRek=${currentTableRow.value.cwRek}`)) as any
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '修改成功'
    })
    getTableList()
  } else {
    ElMessage({
      type: 'error',
      message: res.message
    })
  }
}

const isLoading2 = ref(false)
const tableData2 = ref([]) as any
const tableHeader2 = ref([
  {
    change: true,
    backgroundColor: true,
    width: '120px',
    label: '物料编码',
    prop: 'mtlNo'
  },
  {
    change: true,
    label: '材料颜色',
    prop: 'mtlColor'
  },
  {
    change: true,
    label: '材料名称',
    prop: 'mtlName',
    width: '200px'
  },
  {
    change: true,
    label: '规格',
    prop: 'mtlSpec',
    width: '55px'
  },
  {
    change: true,
    label: '单位',
    prop: 'mtlUnit',
    width: '55px'
  },
  {
    change: true,
    label: '需求用量',
    prop: 'reqQty'
  },
  {
    change: true,
    label: '原仓应发量',
    prop: 'actQty'
  },
  {
    change: true,
    label: '补单入库量',
    prop: 'subQty'
  },
  {
    change: true,
    label: '责任用量',
    prop: 'actQty1'
  },
  {
    disable: true,
    label: '单价',
    prop: 'price',
    width: '55px'
  }
])
const getTableList2 = debounce(async () => {
  isLoading2.value = true
  let tableDataList = (await service.post<any, any>(`/mtlCosts/suppDetQuery?slipNo=${currentTableRow.value.slipNo}`)) as any
  isLoading2.value = false
  tableData2.value = tableDataList.mtlDtos.map((item: any) => {
    if (item.price) item.backgroundColor = '#80FF00'
    item.change = 'Y'
    item.disableConfirm = true
    if (currentTableRow.value.financeFlag2 === 'Y') item.disable = true
    return item
  })
  tableData3.value = tableDataList.dutyDtos
  tableData6.value = tableDataList.dutyDtos
  currentRow2()
  currentRow3()
}, 500)
// 点击表给另一张表传数据
const currentTableRow2 = ref({}) as any
const currentRow2 = async (row: any = tableData2.value[0]) => {
  currentTableRow2.value = row
  getTableList4()
  getTableList5()
}
const fillUnitPrice = async () => {
  const res = (await LoginWork.put(
    `/mtlCosts/suppPriceUpdate?mtlNo=填充单价&slipNo=${currentTableRow.value.slipNo}&price=${currentTableRow2.value.price}`
  )) as any
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: res.message
    })
    getTableList2()
  } else {
    ElMessage({
      type: 'error',
      message: res.message
    })
  }
}
const confirmChange2 = async (row: any) => {
  const res = (await LoginWork.put(`/mtlCosts/suppPriceUpdate?mtlNo=${row.mtlNo}&slipNo=${currentTableRow.value.slipNo}&price=${row.price}`)) as any
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '修改成功'
    })
    getTableList2()
  } else {
    ElMessage({
      type: 'error',
      message: res.message
    })
  }
}

// 表三模块
const tableHeader3 = ref([
  {
    change: true,
    label: '责任归属',
    prop: 'dutyName'
  },
  {
    change: true,
    label: '部门',
    prop: 'deptName'
  },
  {
    change: true,
    label: '责任用量',
    prop: 'dutyQty'
  },
  {
    change: true,
    label: '责任金额',
    prop: 'dutyAmt',
    width: '85'
  },
  {
    label: '免扣金额',
    prop: 'freeAmt',
    width: '85'
  },
  {
    change: true,
    label: '人工费用',
    prop: 'laborAmt'
  },
  {
    change: true,
    label: '扣款金额',
    prop: 'amt'
  }
])
const tableData3 = ref([])
const isLoading3 = ref(false)

const currentTableRow3 = ref({}) as any
const currentRow3 = async (row: any = tableData3.value[0]) => {
  currentTableRow3.value = row
}

// 表四模块
const tableHeader4 = ref([
  {
    label: '材料名称',
    prop: 'subMtlName'
  },
  {
    label: '单价',
    prop: 'price'
  }
])
const tableData4 = ref([])
const isLoading4 = ref(false)
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData4 = ref<summaryDataType[]>([
  {
    index: 1,
    num: 0
  }
])
const getTableList4 = async () => {
  isLoading4.value = true
  let tableDataList = await service.post<any, any>(`/mtlCosts/fitSubQuery?mtlNo=${currentTableRow2.value.mtlNo}`)
  isLoading4.value = false
  tableData4.value = tableDataList.subs
  summaryData4.value[0].num = tableDataList.sum
  // currentRow4()
}
const currentTableRow4 = ref({}) as any
const currentRow4 = async (row: any = tableData.value[0]) => {
  currentTableRow4.value = row
}

// 表五模块
const tableHeader5 = ref([
  {
    label: '材料名称',
    prop: 'subMtlName'
  },
  {
    label: '单价',
    prop: 'price'
  }
])
const tableData5 = ref([])
const isLoading5 = ref(false)
const summaryData5 = ref<summaryDataType[]>([
  {
    index: 1,
    num: 0
  }
])
const getTableList5 = async () => {
  isLoading5.value = true
  let tableDataList = await service.post<any, any>(`/mtlCosts/fitSubQuery?mtlNo=${currentTableRow2.value.mtlNo}`)
  isLoading5.value = false
  tableData5.value = tableDataList.subs2
  summaryData5.value[0].num = tableDataList.sum2
  // currentRow5()
}
const currentTableRow5 = ref({}) as any
const currentRow5 = async (row: any = tableData.value[0]) => {
  currentTableRow5.value = row
}

// 表六模块
const tableHeader6 = ref([
  {
    label: '冲裁',
    prop: 'laborAmtCut'
  },
  {
    label: '手工',
    prop: 'laborAmtCut2'
  },
  {
    label: '工艺',
    prop: 'laborAmtCut3'
  },
  {
    label: '针车',
    prop: 'laborAmtStitch'
  },
  {
    label: '成型',
    prop: 'laborAmtLast'
  }
])
const tableData6 = ref([])
const isLoading6 = ref(false)
const getTableList6 = async () => {
  isLoading6.value = true
  let tableDataList = await service.post<any, any>('/pcFactorQuery/queryMtlHead', {
    brand: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
      ?.selectValue,
    color: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入颜色'
    )?.inputValue,
    deliveryEndDate: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '交期'
    )?.dateValue?.[1],
    deliveryStartDate: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '交期'
    )?.dateValue?.[0],
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    shortStatus: cfmFlag() //	有无欠数(Y/N)	string	body	true
  })
  isLoading6.value = false
  tableData6.value = tableDataList.list
  // currentRow6()
}
const currentTableRow6 = ref({}) as any
const currentRow6 = async (row: any = tableData.value[0]) => {
  currentTableRow6.value = row
}

const getSelectList = async () => {
  const mtlDept = formList.value.find(
    (item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '补料部门'
  ) as any
  const mtlDeps = await service.get<any, any>('/back/deptQuery')
  mtlDeps.forEach((Vendor: any) => {
    mtlDept.selectOptions.push({
      optionLabel: Vendor.deptName,
      optionValue: `${Vendor.deptNo}`,
      LeftLabel: `${Vendor.deptNo}`,
      RightLabel: `${Vendor.deptName}`
    })
  })
  formList.value[3].selectOptions?.push(
    {
      optionValue: '普通开补',
      optionLabel: '普通开补',
      optionKey: '1'
    },
    {
      optionValue: '鞋面全套',
      optionLabel: '鞋面全套',
      optionKey: '2'
    },
    {
      optionValue: '成型全套',
      optionLabel: '成型全套',
      optionKey: '3'
    },
    {
      optionValue: '原材料开补',
      optionLabel: '原材料开补',
      optionKey: '4'
    }
  )
}
onMounted(() => {
  getSelectList()
})

// Dialog确认添加/修改按钮
const confirm3 = async (obj: any, dialogVisible: any, title: any) => {
  // 向服务器发送请求，更新外派单信息
  if (title === '修改') {
    const res = (await LoginWork.post(
      `/mtlCosts/suppDutyPriceUpdate?slipNo=${currentTableRow.value.slipNo}&dutyName=${currentTableRow3.value.dutyName}&freeAmt=${Number(
        obj.freeAmt
      )}`
    )) as any
    // console.log(typeof obj.freeAmt)
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
      getTableList2()
      dialogVisible.value = false
    } else {
      JMessage.error(res.message)
    }
  }
}
</script>

<style lang="less" scoped></style>
<style>
@media print {
  .printContent2 {
    page-break-after: always;
  }

  .page-header {
    position: fixed;
    top: 0;
    width: 100%;
    background-color: white;
    border-bottom: 1px solid black;
    padding: 10px 0;
    text-align: center;
  }

  .page-content {
    margin-top: 50px; /* 确保内容不与页头重叠 */
  }

  @page {
    margin: 20mm;
  }
}
</style>
